#! /bin/bash

BUILDDIR='/tmp/build/'
GOSRC=$GOPATH/src
abs=`pwd`

. $GOSRC/xp/script/env.sh

# 检查包名是否合法
if [[ ! -d $abs ]]; then
	echo "# $abs is not a dir."
	exit 3
fi
if [[ ! $abs =~ $GOSRC ]]; then
	echo "# $abs is not a go package."
	exit 7
fi

# 根据包名生成唯一的可执行文件名称
package=${abs##$GOSRC}
package=${package##/}
service=$package
service=${service%%/}
service=${service//\//_}
if [[ "$service" == "" ]]; then
	echo "# $abs is not a package."
	exit 4
fi
service="$service"

cd $GOSRC/$package
ldflags="-X 'xp/lib/md.service=$service'"
ldflags+=" -X 'xp/lib/md.build=`date +%Y-%m-%dT%H:%M:%S%:z`'"
ldflags+=" -X 'xp/lib/md.branch=`git rev-parse --abbrev-ref HEAD`'"
ldflags+=" -X 'xp/lib/md.revision=`git describe --long --dirty --tags --always`'"
ldflags+=" -X 'xp/lib/md.hostname=`hostname`'"

go generate ./...
# 生成编译目录
mkdir -p $BUILDDIR
cd $BUILDDIR

echo "# Building $package ..."
go build $@ -ldflags "$ldflags" -o "$service" $package || exit 6
if [ -x $service ]; then
	mv $service $abs/
fi
rm -rf $BUILDDIR

# 使用nohup保持后台运行
nohup ./$service & 
